package com.juma.cartridge.rlock;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 锁续租线程
 * @ClassName LeaseTask
 * @Description
 * @Author zhuangguangyou
 * @Date 2019年7月24日 下午4:07:07
 * @Version 1.0
 *
 */
public class LeaseTask implements Runnable {

	private AtomicBoolean running;
	private DelayQueue<RLock> leaseQueue;
	
	private static final Logger log = LoggerFactory.getLogger(LeaseTask.class);
	
	public LeaseTask(DelayQueue<RLock> queue) {
		this.running = new AtomicBoolean(true);
		this.leaseQueue = queue;
	}
	
	public void close() {
		running.set(false);
	}
	
	public boolean isRunning() {
		return running.get();
	}
	
	@Override
	public void run() {
		
		while(running.get()) {
			try {
				log.debug("获取需要续租的锁对象...");
				RLock lock = leaseQueue.poll(30, TimeUnit.SECONDS);
				if(lock!=null && lock.isLocked() && !lock.isExpired()) {
					log.debug("开始续租锁[id={}]",lock.getId());
					lock.lease();
					leaseQueue.add(lock); //重新放入续租队列
				}
			}catch(InterruptedException ie) {
				break;
			}catch(Exception e) {
				log.info(e.getMessage(),e);
			}
		}
		log.info("续租线程退出!");
	}
}
